//
//  HeaterInstallationTypeView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/7/27.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
class HeaterInstallationTypeView: View {
    @objc dynamic var viewModel = InstallationTypeViewModel()
    lazy var disposeBag = DisposeBag()
    //
    var additionalTipBtnClosure: (()->Void)?
    //四个installation type 按钮
    let newBuildingLabel = OptionTypeLabel(HeaterInstallationTypeName.NewBuilding.rawValue)
    let replaceSolarLabel =  OptionTypeLabel(HeaterInstallationTypeName.ReplacedSolarWarterHeater.rawValue)
    let replaceElectricLabel =  OptionTypeLabel(HeaterInstallationTypeName.ReplacedElectricHeater.rawValue)
    let replaceGasLabel =  OptionTypeLabel(HeaterInstallationTypeName.ReplaceGasWaterHeater.rawValue)
    let firtInstallLabel =  OptionTypeLabel(HeaterInstallationTypeName.FirstSolarWaterHeaterAtExistingBuilding.rawValue)
    let otherLabel =  OptionTypeLabel(HeaterInstallationTypeName.Other.rawValue)
    let installationTypeDescripLabel = ContentLabel(R.font.interRegular(size: 13), hexStr: "#292D3266")
    lazy var installationTypeRequiredLabel: BaseLabel = {
        return ViewFactory.shared.generateRequiredLabel()
    }()
    //additional infomation
    var additionalInfoTitleView: LabelWithRedStarView!
    lazy var additionalInfoTextView: TextViewWithRequiredView = {
        let view = TextViewWithRequiredView(.addtionalInfo)
        view.textView.placeholder = ""//必须设置，否则不会调用
        view.textView.limitLength = 4000
        view.textView.limitLabelFont = R.font.interRegular(size: 14)
        view.textView.limitLabelColor = UIColor(hexStr: "#292D3299")
        return view
    }()
    
    override func setUpView() {
        //1.installationType title
        let installationTypeTitle = LabelWithRedStarView(R.string.localizable.installationType())
        self.addSubview(installationTypeTitle)
        installationTypeTitle.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //
        let newStackView = UIStackView(arrangedSubviews: [newBuildingLabel,replaceElectricLabel])
        newStackView.axis = .horizontal
        newStackView.distribution = .fillProportionally//根据每个子视图里面内容的尺寸来进行填充操作
        newStackView.spacing = 8
        self.addSubview(newStackView)
        newStackView.snp.makeConstraints { (make) in
            make.top.equalTo(installationTypeTitle.snp.bottom).offset(12)
            make.left.equalTo(installationTypeTitle)
            make.right.lessThanOrEqualToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //replaceSolarLabel
        self.addSubview(replaceSolarLabel)
        replaceSolarLabel.snp.makeConstraints { (make) in
            make.top.equalTo(newStackView.snp.bottom).offset(8)
            make.left.equalTo(installationTypeTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //firtInstallLabel
        self.addSubview(firtInstallLabel)
        firtInstallLabel.snp.makeConstraints { (make) in
            make.top.equalTo(replaceSolarLabel.snp.bottom).offset(8)
            make.left.equalTo(installationTypeTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        let otherStackView = UIStackView(arrangedSubviews: [replaceGasLabel,otherLabel])
        otherStackView.axis = .horizontal
        otherStackView.distribution = .fillProportionally//根据每个子视图里面内容的尺寸来进行填充操作
        otherStackView.spacing = 8
        self.addSubview(otherStackView)
        otherStackView.snp.makeConstraints { (make) in
            make.top.equalTo(firtInstallLabel.snp.bottom).offset(8)
            make.left.equalTo(installationTypeTitle)
            make.right.lessThanOrEqualToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //installationTypeDescripLabel
        installationTypeDescripLabel.textAlignment = .left
        installationTypeDescripLabel.numberOfLines = 0
        self.addSubview(installationTypeDescripLabel)
        installationTypeDescripLabel.snp.makeConstraints { (make) in
            make.top.equalTo(otherStackView.snp.bottom).offset(8)
            make.left.equalTo(installationTypeTitle)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
        }
        //必填项tip
        self.addSubview(installationTypeRequiredLabel)
        installationTypeRequiredLabel.snp.makeConstraints { (make) in
            make.top.equalTo(installationTypeDescripLabel.snp.bottom).offset(2)
            make.left.equalTo(installationTypeTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.Additional Information
        additionalInfoTitleView = LabelWithRedStarView(R.string.localizable.additionalUpgradeSystemInformation())
        additionalInfoTitleView.titleLabel.numberOfLines = 0
        self.addSubview(additionalInfoTitleView)
        additionalInfoTitleView.snp.makeConstraints { (make) in
            make.top.equalTo(installationTypeRequiredLabel.snp.bottom).offset(20)
            make.left.equalTo(installationTypeTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.1.Additional Information textview
        self.addSubview(additionalInfoTextView)
        additionalInfoTextView.snp.makeConstraints { (make) in
            make.top.equalTo(additionalInfoTitleView.snp.bottom).offset(12)
            make.left.equalTo(installationTypeTitle)
            make.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //new
        newBuildingLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.NewBuilding)
        }).disposed(by: self.disposeBag)
        //replaceGasLabel
        replaceGasLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.ReplaceGasWaterHeater)
        }).disposed(by: self.disposeBag)
        //replaceSolarLabel
        replaceSolarLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.ReplacedSolarWarterHeater)
        }).disposed(by: self.disposeBag)
        //replaceElectricLabel
        replaceElectricLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.ReplacedElectricHeater)
        }).disposed(by: self.disposeBag)
        //firtInstallLabel
        firtInstallLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.FirstSolarWaterHeaterAtExistingBuilding)
        }).disposed(by: self.disposeBag)
        //otherLabel
        otherLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.Other)
        }).disposed(by: self.disposeBag)
        //
        additionalInfoTextView.endEditingClosure = {[weak self] (text) in
            self?.viewModel.additional_upgrade_system_details = text.trimmingCharacters(in: .whitespacesAndNewlines)
            self?.checkIfRequirdAddtional(self?.viewModel.heater_installation_type)
        }

        additionalInfoTitleView.showRedStar(false)
    }
    func setData(_ model: InstallationTypeViewModel, editFlag: Bool = false){
        self.viewModel = model
        self.selectInstallationType(self.viewModel.heater_installation_type)
        if self.viewModel.additional_upgrade_system_details.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: .newlines) != ""{
            self.additionalInfoTextView.textView.text = self.viewModel.additional_upgrade_system_details
            self.additionalInfoTextView.textView.textChange(Notification(name: UITextView.textDidChangeNotification))//通知隐藏placeholder
        }
        //检查Additional/Upgrade System Information是否是必填项，显示red star
        self.checkIfRequirdAddtional(self.viewModel.heater_installation_type)
        //
        if editFlag {
            self.validateAllRequiredFieldWhenEdit()
        }
    }
    //
    private func selectInstallationType(_ type: HeaterInstallationTypeValue){
        self.newBuildingLabel.setUnSelect()
        self.replaceGasLabel.setUnSelect()
        self.replaceSolarLabel.setUnSelect()
        self.replaceElectricLabel.setUnSelect()
        self.firtInstallLabel.setUnSelect()
        self.otherLabel.setUnSelect()
        //
        self.installationTypeDescripLabel.textColor = UIColor(hexStr: "#292D3266")
        var tipMsg = ""
        switch type {
        case .NewBuilding:
            self.newBuildingLabel.setSelect()
            tipMsg = "The first install of solar water heater at a new building"
        case .ReplacedElectricHeater:
            self.replaceElectricLabel.setSelect()
            self.installationTypeDescripLabel.textColor = UIColor(hexStr: "#FC7C13")//此处改成橙色显示
            tipMsg = "Please confirm if this address has installed solar waters before? If yes,please choose \"Replace solar water heater\"."
        case .ReplaceGasWaterHeater:
            self.replaceGasLabel.setSelect()
            tipMsg = "Completely remove existing gas water heater and install a new solar water heater as a replacement"
        case .ReplacedSolarWarterHeater:
            self.replaceSolarLabel.setSelect()
            tipMsg = "Completely remove existing solar water heater system and install a new one as a replacement"
        case .FirstSolarWaterHeaterAtExistingBuilding:
            self.firtInstallLabel.setSelect()
            tipMsg = "The first install of solar water heater at an existing building"
        case .Other:
            self.otherLabel.setSelect()
            tipMsg = ""
        default:
            break
        }
        //隐藏必填项tip msg
        self.installationTypeDescripLabel.text = tipMsg
        self.installationTypeRequiredLabel.text = ""
        self.viewModel.heater_installation_type = type//创建Job的地方用
        self.checkIfRequirdAddtional(type)
        
    }
    //MARK: - 只用于已创建Job的信息编辑， 进入编辑界面如果save 按钮不可用，要给与相应提示
    private func validateAllRequiredFieldWhenEdit(){
        if self.viewModel.heater_installation_type == .None {
            self.installationTypeRequiredLabel.text = R.string.localizable.thisIsRequired()
        }else{
            self.installationTypeRequiredLabel.text = ""
        }
        self.additionalInfoTextView.checkTextViewIfValid()
    }
    @objc func additionalTipBtnClick(){
        self.endEditing(true)
        self.additionalTipBtnClosure?()
    }
    private func checkIfRequirdAddtional(_ installationType: HeaterInstallationTypeValue?){
        if let type = installationType {//ReplacedSolarWarterHeater， other是必填，其他都是非必填
            if type == .Other{
                additionalInfoTitleView.showRedStar(true)
                additionalInfoTextView.needCheckFlag = true
            }else{
                additionalInfoTitleView.showRedStar(false)
                additionalInfoTextView.needCheckFlag = false
                additionalInfoTextView.checkTextViewIfValid()
                let text = self.additionalInfoTextView.textView.text ?? ""
                if text != "" && Tool().isValidAddtionalInfo(text) == false{
                    additionalInfoTextView.showInvalidMsg(R.string.localizable.additionalUpgradeSystemInformationMustBeBetween7And4000Digits())
                }else{
                    additionalInfoTextView.hideInvalidMsg()
                }
            }
        }else{
            additionalInfoTitleView.showRedStar(false)
        }
    }
}
